import collections
import json
import logging
import os

import hvac
import pandas as pd

from absl import app, flags
from coin.support.key_tool.vault.coin_key_high_dumper import list_keys

FLAGS = flags.FLAGS


def from_file():
  mount_point = FLAGS.mount_point
  client = hvac.Client(url=FLAGS.vault_addr)
  assert client.is_authenticated()
  keys = []
  # [eddys@home-2 coin_deploy]$ binance_hosts=$(awk -F, '{print $3}' binance.txt | grep -v machine | sort | uniq)
  # [eddys@home-2 coin_deploy]$ for i in $binance_hosts; do grep -A1 "Host $i" jaewon_strategy/ssh_config/ssh_config | awk '{print $2}' | xargs; done
  # cat c.txt |awk '{ print "  \"" $1 "\": \"" $2 "\","}' > c.json
  with open(flags.FLAGS.machine_ip_map_path, 'r') as f:
    ip_map = json.load(f)
  df = pd.read_csv(flags.FLAGS.account_infos_path)
  for _, row in df.iterrows():
    item = {}
    path = "trade/{}/{}".format(row['owner'], row['exchange'].lower())
    key_infos = list_keys(client, path, mount_point, True)
    is_spot = True if row['market_type'] == 'Spot' else False
    for key_info in key_infos:
      info = key_info.key_content
      path = info['path']
      if is_spot and 'fut' in path:
        continue
      if not is_spot and 'fut' not in path:
        continue
      owner = info['owner']
      ip_list = "{},{}".format(ip_map[row['machine']], "118.201.95.106")
      if 'strategy-26.ap-northeast-1.megaport' == row['machine']:
        ip_list += ",13.231.60.212,18.176.177.185,18.178.49.195,35.76.19.249,52.193.234.188,54.150.235.3,54.95.13.72"
      if 'strategy-04.ap-northeast-1.megaport' == row['machine']:
        ip_list += ",18.180.187.129"
      item['owner'] = owner
      item['apikey'] = info['access_key']
      item['email'] = "coin-binance-{}@prestolabs.io".format(owner.replace('xunke', '').replace('_swap', '').replace('_portfolio',''))
      item['ip'] = ip_list
      item['machine'] = row['machine']
      item['strategy_name'] = row['strategy_name']
    keys.append(item)
  #print(keys)
  pd.set_option('display.max_colwidth', 200)
  df = pd.DataFrame(keys)
  df.to_csv(FLAGS.output_csv_path)
  with open(FLAGS.output_txt_path, 'w') as f:
    f.write(df.to_string())
  print(df.to_string())


def from_text():
  mount_point = FLAGS.mount_point
  client = hvac.Client(url=FLAGS.vault_addr)
  assert client.is_authenticated()
  keys = []
  #raw_input = 'xunke120_swap,xunke111_swap,xunke104_swap -> 54.199.90.150'
  raw_input = FLAGS.raw_input

  accounts = raw_input.split('->')[0].strip().split(',')
  ips = raw_input.split('->')[1].strip()
  for acc in accounts:
    item = {}
    path = "trade/{}/{}".format(acc, 'binance')
    key_infos = list_keys(client, path, mount_point, True)
    is_spot = False
    email_id = acc.replace('xunke', '').replace('_swap', '')
    for key_info in key_infos:
      info = key_info.key_content
      path = info['path']
      if is_spot and 'fut' in path:
        continue
      if not is_spot and 'fut' not in path:
        continue
      owner = acc
      api_key = info['access_key']
      email = 'coin-binance-{}@prestolabs.io'.format(email_id)
      ip_list = '{},{}'.format(ips, "118.201.95.106")
      print(api_key)
      print(email)
      print(ip_list)
      cmd = './pyrunner cc/experimental/wliang/utils/binance_bind_ip.py --key_path=python/coin_key_high/trade/prestoinv0/binance/trade_key.json --api_key={} --email={} --ip_list={}'.format(api_key, email, ip_list)
      print(cmd)


def main(_):
  from_text()


# VAULT_TOKEN=<token> ./pyrunner cc/experimental/wliang/utils/prepare_bind_ip.py  --mount_point=coin_key_high  --vault_addr=https://laksa.joomo.io:8200
if __name__ == '__main__':
  logging.basicConfig(
      level='DEBUG', format='%(levelname)8s %(asctime)s %(name)s] %(message)s')
  flags.DEFINE_string('vault_addr', None, '')
  flags.DEFINE_string('path', '', '')
  flags.DEFINE_string('mount_point', None, '')
  flags.DEFINE_string('machine_ip_map_path', None, '')
  flags.DEFINE_string('account_infos_path', None, '')
  flags.DEFINE_string('output_csv_path', None, '')
  flags.DEFINE_string('output_txt_path', None, '')
  flags.DEFINE_string('raw_input', None, '')

  app.run(main)
